package com.zhihuichongcheng.application.ui.im.activity;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.app.ActivityCompat;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.sdk.android.oss.ClientException;
import com.alibaba.sdk.android.oss.OSS;
import com.alibaba.sdk.android.oss.ServiceException;
import com.alibaba.sdk.android.oss.callback.OSSCompletedCallback;
import com.alibaba.sdk.android.oss.callback.OSSProgressCallback;
import com.alibaba.sdk.android.oss.internal.OSSAsyncTask;
import com.alibaba.sdk.android.oss.model.ObjectMetadata;
import com.alibaba.sdk.android.oss.model.PutObjectRequest;
import com.alibaba.sdk.android.oss.model.PutObjectResult;
import com.bumptech.glide.Glide;
import com.smartlib.cmnObject.dialog.DialogOnClick;
import com.smartlib.cmnObject.util.DialogUtil;
import com.smartlib.cmnObject.util.ToastOpt;
import com.smartlib.cmnObject.util.Util;
import com.zhihuichongcheng.application.R;
import com.zhihuichongcheng.application.base.BaseActivity;
import com.zhihuichongcheng.application.bean.mine.DepInfo;
import com.zhihuichongcheng.application.bean.mine.PositionInfo;
import com.zhihuichongcheng.application.bean.mine.UserBean;
import com.zhihuichongcheng.application.constant.Constants;
import com.zhihuichongcheng.application.constant.NetworkAPI;
import com.zhihuichongcheng.application.glide.GlideCircleTransform;
import com.zhihuichongcheng.application.net.HttpCallback;
import com.zhihuichongcheng.application.ui.mine.ChangePasswordActivity;
import com.zhihuichongcheng.application.ui.mine.LoginActivity;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Random;

/**
 * Created by 3water on 2016/10/28.
 */

public class ImUserInfoActivity extends BaseActivity implements View.OnClickListener {
    private TextView mTvDepartment, mTvPosition, mTvBJPhone, mTvTjPhone, mTvName, mTvMinPhone, mTvMaxPhone, mTvRemark;
    private String mUserId;
    private ImageView mImAvatar;
    private UserBean mUser;
    private TextView mTvRoomId;
    private String mUpdateIconCameraPath;
    private TextView mTvSendMsg;
    private LinearLayout mLlBeijing, mLlTj;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_im_user_info);
        initView();
        initData();
//        PermissionUtil.hasPermissionInManifest(this, "android.permission.CALL_PHONE");
    }


    private void initView() {
        mLlBeijing = (LinearLayout) findViewById(R.id.ll_beijing);
        mLlTj = (LinearLayout) findViewById(R.id.ll_tianjing);
        mLlBeijing.setOnClickListener(this);
        mLlTj.setOnClickListener(this);
        mTvSendMsg = (TextView) findViewById(R.id.tv_sendMsg);
        mTvRoomId = (TextView) findViewById(R.id.tv_roomId);
        mTvName = (TextView) findViewById(R.id.tv_name);
        mImAvatar = (ImageView) findViewById(R.id.im_avatar);
        setTitle("详细资料");
        mTvDepartment = (TextView) findViewById(R.id.tv_department);
        mTvPosition = (TextView) findViewById(R.id.tv_position);
        mTvBJPhone = (TextView) findViewById(R.id.tv_bjphone);
        mTvTjPhone = (TextView) findViewById(R.id.tv_tjphone);
        mTvMinPhone = (TextView) findViewById(R.id.tv_minPhone);
        mTvMaxPhone = (TextView) findViewById(R.id.tv_maxPhone);
        mTvRemark = (TextView) findViewById(R.id.tv_remark);
        mImAvatar.setOnClickListener(this);
        mTvSendMsg.setOnClickListener(this);
    }

    private void initData() {
        Intent intent = getIntent();
        if (intent != null) {
            if (intent.hasExtra("userId")) {
                mUserId = intent.getStringExtra("userId");
            }
        }
        mUser = spUtil.getObject(mUserId, UserBean.class);
        if(mUser==null)
        {
            ToastOpt.createToast(mContext,"用户不存在");
            return;
        }
        else
        {
            //test
            DepInfo info = mUser.getDept();
            if (info != null) {
                mTvDepartment.setText(info.getDeptName());
            }
            PositionInfo positionInfo = mUser.getPosition();
            if (positionInfo != null) {
                mTvPosition.setText(positionInfo.getPositionName());
            }
            mTvRoomId.setText(mUser.getRoomId());
            mTvBJPhone.setText(mUser.getBeijinMobile());
            mTvTjPhone.setText(mUser.getTianjinMobile());
            mTvMaxPhone.setText(mUser.getMaxPhone());
            mTvMinPhone.setText(mUser.getMinPhone());
            String remark = mUser.getRemark();
            if (!TextUtils.isEmpty(remark)) {
                mTvRemark.setText(mUser.getRemark());
            } else {
                mTvRemark.setText("没添加备注");
            }
            Glide.with(mContext).load(mUser.getLogoUrl()).transform(new GlideCircleTransform(mContext)).placeholder(R.drawable.ic_default_avatar).into(mImAvatar);
            mTvName.setText(mUser.getUserName());
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.rl_change_password:
                Intent intent = new Intent(mContext, ChangePasswordActivity.class);
                intent.putExtra("userId", mUserId);
                startActivity(intent);
                break;
            case R.id.tv_sendMsg:
                Bundle bundle = new Bundle();
                bundle.putString("userId", mUserId);
                startActivity(ChatActivity.class, bundle);
                break;
            case R.id.rl_exit:
                DialogUtil.showSimpleAlertDialog(mContext, new DialogOnClick() {
                    @Override
                    public void onClick(Object o) {
                        app.setUser(null);
                        spUtil.putString("user", "");
                        startActivity(new Intent(mContext, LoginActivity.class));
                    }
                }, "是否推出登陆");
                break;
            case R.id.ll_beijing:
                final String bjPhone = mTvBJPhone.getText().toString();
                if (!TextUtils.isEmpty(bjPhone)&& Util.isMobileNO(bjPhone)) {
                    DialogUtil.showUploadFile(mContext, "直接打电话", "复制文本", new DialogOnClick<String>() {
                        @Override
                        public void onClick(String s) {
                            Intent intentCall = new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + bjPhone));
                            if (ActivityCompat.checkSelfPermission(ImUserInfoActivity.this, Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {
                                return;
                            }
                            mContext.startActivity(intentCall);
                        }
                    }, new DialogOnClick<String>() {
                        @Override
                        public void onClick(String s) {
                            android.text.ClipboardManager clipboardManager = (android.text.ClipboardManager) mContext.getSystemService(Context.CLIPBOARD_SERVICE);
                            clipboardManager.setText(mTvBJPhone.getText().toString());
                        }
                    });
                }
                break;
            case R.id.ll_tianjing:
                final String tjPhone = mTvTjPhone.getText().toString();
                if (!TextUtils.isEmpty(tjPhone)&& Util.isMobileNO(tjPhone)) {
                    DialogUtil.showUploadFile(mContext, "直接打电话", "复制文本", new DialogOnClick<String>() {
                        @Override
                        public void onClick(String s) {
                            Intent intentCall = new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + tjPhone));
                            if (ActivityCompat.checkSelfPermission(ImUserInfoActivity.this, Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {
                                return;
                            }
                            mContext.startActivity(intentCall);
                        }
                    }, new DialogOnClick<String>() {
                        @Override
                        public void onClick(String s) {
                            android.text.ClipboardManager clipboardManager = (android.text.ClipboardManager) mContext.getSystemService(Context.CLIPBOARD_SERVICE);
                            clipboardManager.setText(mTvBJPhone.getText().toString());
                        }
                    });
                }
                break;
            default:
                break;
        }
    }


    /***
     * 拍照
     */
    private void getImageFromCamera() {
        String state = Environment.getExternalStorageState();
        mUpdateIconCameraPath = Constants.Const_Cache_Dir + System.currentTimeMillis() + ".png";
        if (state.equals(Environment.MEDIA_MOUNTED)) {
            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            File dir = new File(Constants.Const_Cache_Dir);
            if (!dir.exists()) {
                dir.mkdirs();
            }
            File f = new File(mUpdateIconCameraPath);//localTempImgDir和localTempImageFileName是自己定义的名字
            Uri u = Uri.fromFile(f);
            intent.putExtra(MediaStore.Images.Media.ORIENTATION, 0);
            intent.putExtra(MediaStore.EXTRA_OUTPUT, u);
            startActivityForResult(intent, Constants.REQUESTCODE_CAPTURE_CAMEIA);
        } else {
            Toast.makeText(mContext, "请确认已经插入SD卡", Toast.LENGTH_LONG).show();
        }
    }

    /***
     * 从相册选择
     */
    private void selectImageFromAlbum() {
        Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
        intent.setType("image/*");//相片类型
        startActivityForResult(intent, Constants.REQUESTCODE_ALBUM);
    }

    private void initCrope(Uri imageUri) {
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(imageUri, "image/*");
        intent.putExtra("crop", "true");
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        intent.putExtra("outputX", 250);
        intent.putExtra("outputY", 250);
        intent.putExtra("return-data", true);
        startActivityForResult(intent, Constants.REQUESTCODE_CHOOSE_PIC);
    }


    public void saveBitmapFile(Bitmap bitmap) {
        File file = new File(mUpdateIconCameraPath);//将要保存图片的路径
        try {
            BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file));
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bos);
            bos.flush();
            bos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void updateOss(final OSS oss, final String path) {
        mUser = app.getUser();
        if (mUser == null) {
            ToastOpt.createToast(mContext, "请先登陆");
            return;
        }
        DialogUtil.showLoadDiadlog(mContext);
        // 指定数据类型，没有指定会自动根据后缀名判断
        new Thread(new Runnable() {
            @Override
            public void run() {
                ObjectMetadata objectMeta = new ObjectMetadata();
                objectMeta.setContentType("image/jpeg");
                Random random = new Random(1000);//指定种子数字
                final String name = System.currentTimeMillis() + random.nextInt() + ".png";
                // 构造上传请求
                PutObjectRequest put = new PutObjectRequest("yirimao", name, path);
                put.setMetadata(objectMeta);
                try {
                    PutObjectResult putObjectResult = oss.putObject(put);
                } catch (ClientException
                        e) {
                    e.printStackTrace();
                } catch (ServiceException e) {
                    e.printStackTrace();
                }

                // 异步上传时可以设置进度回调
                put.setProgressCallback(new OSSProgressCallback<PutObjectRequest>() {
                    @Override
                    public void onProgress(PutObjectRequest request, long currentSize, long totalSize) {
                        // 在这里可以实现进度条展现功能
                        Log.d("PutObject", "currentSize: " + currentSize + " totalSize: " + totalSize);
                    }
                });
                OSSAsyncTask task = oss.asyncPutObject(put, new OSSCompletedCallback<PutObjectRequest, PutObjectResult>() {
                    @Override
                    public void onSuccess(PutObjectRequest request, PutObjectResult result) {
                        HashMap<String, String> params = new HashMap<String, String>();
                        String token = mUser.getToken();
                        params.put("token", mUser.getToken());
                        params.put("logoUrl", Constants.OSS_ENDPOINT + "/" + name);
                        mManager.post(NetworkAPI.UpdateFile, new HttpCallback() {
                            @Override
                            public void onSuccess(int code, String value, String msg) {
                                ToastOpt.createToast(mContext, "图片上传成功");
                                finish();
                                DialogUtil.dismiss(mContext);
                            }

                            @Override
                            public void onFailure(String value) {
                                ToastOpt.createToast(mContext, "图片上传失败");
                                DialogUtil.dismiss(mContext);
                            }
                        }, params);

                    }

                    @Override
                    public void onFailure(PutObjectRequest request, ClientException clientExcepion, ServiceException serviceException) {
                        // 请求异常
                        if (clientExcepion != null) {
                            // 本地异常如网络异常等
                            clientExcepion.printStackTrace();
                        }
                        DialogUtil.dismiss(mContext);
                        ToastOpt.createToast(mContext, "图片上传失败，请重新上传");
                        return;
                    }
                });
            }
        }).start();

    }
}
